# 角色管理
from flask import Blueprint,request
from flaskDemo.config.config import Config
from flaskDemo.sql.mysql_db import mysql_db
from flaskDemo.extensions.success import list_result,map_result
from flaskDemo import socketio
import redis
role = Blueprint('role',__name__)
err = Config.ERR
redis_client = redis.Redis(host='192.168.1.176', port=6379, db=0, max_connections=10,decode_responses=True)
@role.route("/get_role_list")
def get_role_list():
    sql = "select * from system_role"
    with mysql_db() as db:
        result = db.fetch_all(sql)
        return list_result(result)


@role.route("/getRoleMenuTree")
def getRoleMenuTree():
    params = request.values
    menuType = params.get("menuType")
    roleId = params.get("roleId")
    with mysql_db() as db:
        sql = f"select * from system_menu where menu_type = {menuType} and pid = '0'"
        result = db.fetch_all(sql)
        def circulate_child(item):
            sql = f"select * from system_menu where pid = '{item['id']}' and menu_type = {menuType}"
            child_result = db.fetch_all(sql)
            if len(child_result) > 0:
                item["children"] = child_result
                for itemChild in child_result:
                    itemChild["auth"] = getPermissionList(itemChild, menuType)
                    itemChild["checkedPermissions"] = getPermissionedList(roleId, itemChild['id'])
                    circulate_child(itemChild)
            else:
                item["auth"] = item["auth"] = getPermissionList(item, menuType)
                item["children"] = []
                return -1

        if len(result) > 0:
            for item in result:
                item["auth"] = getPermissionList(item,menuType)
                item["checkedPermissions"] = getPermissionedList(roleId, item['id'])
                circulate_child(item)

        return list_result(result)
# 获取菜单下有那些按钮权限
def getPermissionList(item,menuType):
    with mysql_db() as db:
        menuType = int(menuType) + 1
        sql = f"select * from system_menu where pid = '{item['id']}' and menu_type = {menuType}"
        result = db.fetch_all(sql)
        return result

'''
    获取角色权限
'''
def getPermissionedList(roleId,pid):
    with mysql_db() as db:
        sql = f"select a.role_id,GROUP_CONCAT(DISTINCT a.menu_id) as menuId from system_role_menu a left join system_menu b on a.menu_id = b.id  group by b.pid HAVING FIND_IN_SET(a.role_id,'{roleId}') and b.pid = '{pid}'"
        result = db.fetch_one(sql)
        if result is not None:
            idArr = result["menuId"].split(",")
            return idArr
        else:
            return []

'''
保存用户权限
'''
@role.route("/saveRoleMenu", methods=['POST'])
def saveRoleMenu():
    params = request.json
    roleId = params.get("roleId")
    permissions = params.get("permissions")
    menuType = params.get("menuType")
    with mysql_db() as db:
        sql = f"delete from system_role_menu where role_id = '{roleId}' and menu_type = {menuType}"
        db.delete(sql)
        if len(permissions) != 0:
            sql = "insert into system_role_menu (role_id,menu_id,menu_type) values"
            sql_cnt = 0;
            for permission in permissions:
                if sql_cnt == len(permissions) - 1:
                    sql += f"('{roleId}','{permission}',{menuType});"
                else:
                    sql += f"('{roleId}','{permission}',{menuType}),"
                sql_cnt = sql_cnt + 1
            result = db.insert(sql)
        db.conn.commit()
        return map_result(result)

@role.route("/sendMessage",methods=['GET'])
def sendMessage():
    ls1 = redis_client.get("77dbe89a-1b")
    socketio.emit("test3", {"data":1,"ls":ls1},room=ls1)
    return map_result()
